package com.clss.emergencycall.utils;

import android.content.Context;
import android.content.SharedPreferences;
import com.amap.api.location.AMapLocation;
import com.clss.emergencycall.EmergencyApplication;
import com.clss.emergencycall.bean.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * SharedPreferences帮助类，保存用户信息等内容
 * Created by LiuV on 2017/6/12.
 */

public class SpHelper {
    private static final String TAG = "SpHelper";

    private static final String PROJECT_NAME = "pelple_safety";
    private static final String TOKEN = "token";
    private static final String NAME = "name";
    private static final String ID = "id";
    private static final String USER_NAME = "user_name";
    private static final String PHONE = "phone";
    private static final String USER_ID = "user_id";
    private static final String IS_VERIFY = "is_verify";
    private static final String BIRTH = "birthday";
    private static final String LOGIN_HOST = "LOGIN_HOST";
    private static final String NICK_NAME = "nick_name";
    private static final String UNOION_ID = "unionId";
    private static final String WX_LOGIN_STATE = "wx_login_state";

    private static final String FIRE_INSPECTION_ROLE = "fire_inspection_role";
    private static final String LAST_VERSION_CHECK_TIME = "last_version_check_time";
    private static final String SHARE_COMMON_ARRAY = "share_commmon_array";
    public static final String LOCATION_HOST = "LOCATION_HOST"; // 登录时存的host 实名认证和修改密码的时候用  漫游修改密码登录失效

    private static final String INSPECTION_TASKS_BEAN_LIST = "inspection_tasks_bean_list";

    public static final String SAFE_ID = "SAFE_ID";
    private static final String NEW_NOTIFICATION_ID = "new_notification_id";
    private static final String HUB_CURRENT_HOST = "hub_current_host";
    private static final String HUB_BACKUP_HOST = "hub_backup_host";
    private static final String FACE_PHOTO = "face_photo";
    private static final String SECRET = "secret";
    private static final String SCANNER_TOKEN = "scanner_token";
    private static final String MY_INFO_HAS_UPDATE = "my_info_has_update";


    private static final String PATCH_VERSION = "PATCH_VERSION";
    //新版本更新app版本
    private static final String APP_VERSION = "APP_VERSION";

    /**
     * 是否首次进入创建队伍
     */
    public static final String CREAT_TEAM_FIRST = "CREAT_TEAM_FIRST";
    /**
     * 是否有值 代表是否演示报警
     */
//    public static final String DEMONSTRATE_THE_ALARM = "Demonstrate_the_alarm";
    /**
     * 工作模式
     * 0 默认正常模式，从当前位置的hub获取服务器地址
     * 1 演示模式，当前位置hub获取的服务器
     * 2 demo服务器，不使用从hub获取到的服务器地址
     * 3 demo服务器并开启演示模式
     */
    private static final String WORKING_MODE = "WORKING_MODE";
    public static final int WORKING_MODE_NORMAL = 0;
    public static final int WORKING_MODE_SHOW = 1;
    public static final int WORKING_MODE_DEMO = 2;
    public static final int WORKING_MODE_DEMO_SHOW = 3;

    /**
     * AMAPLOCATION_INFO: 单独记录一个定位code 判断是否首次进入
     */
    public static final String AMAPLOCATION_INFO = "location_codeSC";
    /**
     * 判断是否首次进入（使用切换应用图标功能）
     */
    public static final String FRIST_CHANGE_LOGO = "FRIST_CHANGE_LOGO";

    /**
     * 单独记录一个进入线索列表传到后端的code 用于线索相关所有接口
     */
    public static final String AMAPLOCATION_CLUE_CODE = "AMAPLOCATION_CLUE_CODE";
    /**
     * 后端返回的地址信息 有值代表用户选择过
     */
    public static final String AMAPLOCATION_PROVINCE = "Amap_location_province";
    public static final String AMAPLOCATION_CITY = "Amap_location_city";
    public static final String AMAPLOCATION_AREA = "Amap_location_area";
    public static final String AMAPLOCATION_INFO_AREA = "Amap_location_codeSC_area";
    /**
     * 围栏中定位到的位置
     * id
     */
    public static final String FENCE_PROVINCE = "FENCE_PROVINCE";
    public static final String FENCE_CITY = "FENCE_CITY";
    public static final String FENCE_AREA = "FENCE_AREA";
    public static final String FENCE_CODE = "FENCE_CODE";
    public static final String FENCE_ID = "FENCE_ID";

    /**
     * 定位存储aMapLocation信息
     */
    public static final String LOCATION_LAT = "location_lat_people_safe";
    public static final String LOCATION_LNG = "location_lng_people_safe";
    public static final String LOCATION_ADDRESS = "location_address_people_safe";
    public static final String LOCATION_PROVINCE = "location_provinve_people_safe";
    public static final String LOCATION_CITY = "location_city_people_safe";
    public static final String LOCATION_AREA = "location_area_people_safe";
    public static final String LOCATION_AREA_CODE = "location_area_code_people_safe";
    public static final String LOCATION_STREET = "location_street_code_people_safe";
    public static final String LOCATION_COUNTRY = "location_country_local_people_safe";

    /**
     * topicId本地持久化集合
     */
    private static final String TOPIC_ID_SET = "topic_id_set";
    /*** 本地存储的围栏接口信息*/
    public static final String FENCE_SERVICE_INFO = "FENCE_SERVICE_INFO";
    /*** 记录上一次请求围栏数据的时间 （数据较大一定时间内部重复请求）*/
    public static final String FENCE_SERVICE_TIME = "FENCE_SERVICE_TIME";

    /**
     * 系统用户的id
     */
    private static final String SYS_USER_NAME = "SYS_USER_NAME";
    /**
     * 红点集合
     */
    private static final String MSG_MAP_NONE = "MSG_MAP_NONE";

    private static final String APP_IS_USED = "APP_IS_USED";

    private static final String LAST_ALARM_FINISH_TIME = "LAST_ALARM_FINISH_TIME";

    private static final String SOS_CODE = "SOS_CODE";

    public String getBlackTimes() {
        return getString(BLACK_TIMES);
    }
    public void setBlackTimes(String blackTimes) {
        putString(BLACK_TIMES,blackTimes);
    }
    private static final String BLACK_TIMES = "BLACK_TIMES";

    private SharedPreferences mSharedPreferences;

    private static SpHelper spHelper;

    public static SpHelper getInstance() {
        if (spHelper == null) {
            synchronized (SpHelper.class) {
                if (spHelper == null) {
                    spHelper = new SpHelper();
                    return spHelper;
                }
            }
        }
        return spHelper;
    }

    private SpHelper() {
        this(EmergencyApplication.Companion.getAppContext(), Context.MODE_PRIVATE);
    }

    private SpHelper(Context context, int mode) {
        mSharedPreferences = context.getSharedPreferences(PROJECT_NAME, mode);
    }

    public boolean putString(String key, String value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(key, value);
        return editor.commit();
    }

    public String getString(String key) {
        return mSharedPreferences.getString(key, "");
    }

    public boolean putInt(String key, int value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putInt(key, value);
        return editor.commit();
    }

    public int getInt(String key) {
        return mSharedPreferences.getInt(key, -1);
    }

    public boolean putLong(String key, long value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putLong(key, value);
        return editor.commit();
    }

    public long getLong(String key) {
        return mSharedPreferences.getLong(key, -1);
    }

    public boolean putBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putBoolean(key, value);
        return editor.commit();
    }

    public boolean getBoolean(String key) {
        return mSharedPreferences.getBoolean(key, false);
    }

    private boolean putSet(String key, Set<String> set) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putStringSet(key, set);
        return editor.commit();
    }

    private Set<String> getSet(String key) {
        return mSharedPreferences.getStringSet(key, new HashSet<>());
    }


    public String getToken() {
        return getString(TOKEN);
    }

    public boolean saveToken(String token){
        return putString(TOKEN, token);
    }

    public void saveAll(LoginBean bean) {
        Lg.i(TAG, "---saveAll===" + bean.toString());
        saveToken(bean.getToken());
        putString(USER_NAME, bean.getUserName());
        putString(PHONE, bean.getPhone());
        putString(USER_ID, bean.getUserId());
        putString(NAME, bean.getName());
        putString(ID, bean.getId());
        putString(BIRTH, bean.getBirthday());
        putInt(IS_VERIFY, bean.getIsVerify());
        putString(NICK_NAME, bean.getNickName());
        putString(UNOION_ID, bean.getUnionId());
        putString(FACE_PHOTO, bean.getFacePhoto());
        putString(SECRET, bean.getSecret());
    }

    public void clearAll() {
        LoginBean loginBean = new LoginBean();
        loginBean.setToken("");
        loginBean.setUserName("");
        loginBean.setPhone("");
        loginBean.setUserId("");
        loginBean.setName("");
        loginBean.setId("");
        loginBean.setBirthday("");
        loginBean.setIsVerify(-1);
        loginBean.setNickName("");
        loginBean.setUnionId("");
        loginBean.setFacePhoto("");
        loginBean.setSecret("");
        saveAll(loginBean);
        clearLocalLocation();
        clearPeoLocation();
        clearTopicIdSet();
        setFenceSite("", "", "", "", "");
        setWxLoginState("");
        putSet(SOS_CODE,  new HashSet<>());
    }

    public void clearLocalLocation() {
        putString(AMAPLOCATION_INFO, "");
        putAllSite();
    }

    /**
     * 清空用户选择的后端地址
     */
    public void putAllSite() {
        putString(SpHelper.AMAPLOCATION_INFO_AREA, "");
        putString(SpHelper.AMAPLOCATION_PROVINCE, "");
        putString(SpHelper.AMAPLOCATION_CITY, "");
        putString(SpHelper.AMAPLOCATION_AREA, "");
    }

    /**
     * 清除高德定位地址
     */
    public void clearPeoLocation() {
        putString(LOCATION_LAT, "");
        putString(LOCATION_LNG, "");
        putString(LOCATION_ADDRESS, "");
        putString(LOCATION_AREA, "");
        putString(LOCATION_AREA_CODE, "");
        putString(LOCATION_CITY, "");
        putString(LOCATION_PROVINCE, "");
    }


    /**
     * 存储用户选择的后端地址
     */
    public void putAllSite(String adCode, String provice, String city, String area) {
        putString(SpHelper.AMAPLOCATION_INFO_AREA, adCode);
        putString(SpHelper.AMAPLOCATION_PROVINCE, provice);
        putString(SpHelper.AMAPLOCATION_CITY, city);
        putString(SpHelper.AMAPLOCATION_AREA, area.isEmpty() ? city : area);
    }


    /**
     * 存储高德定位地址
     */
    public void setLatLng(AMapLocation aMapLocation) {
        Lg.i(TAG, "---setLatLng===" + aMapLocation);
        String lastLat = getString(LOCATION_LAT);
        String lastLng = getString(LOCATION_LNG);
        if (!lastLat.isEmpty()) {
            double lastLatd = Double.valueOf(lastLat);
            double lastLngd = Double.valueOf(lastLng);

            int num = PublicUtils.getTance(lastLatd, lastLngd, aMapLocation.getLatitude(), aMapLocation.getLongitude());
            if (num < 20) {
                return;
            }
        }
        putString(LOCATION_LAT, aMapLocation.getLatitude() + "");
        putString(LOCATION_LNG, aMapLocation.getLongitude() + "");
    }

    public void setLocation(AMapLocation aMapLocation) {
        Lg.i(TAG, "---setLocation===" + aMapLocation);
        putString(LOCATION_ADDRESS, aMapLocation.getAddress() + "");
        putString(LOCATION_AREA, aMapLocation.getDistrict() + "");
        putString(LOCATION_AREA_CODE, aMapLocation.getAdCode() + "");
        putString(LOCATION_CITY, aMapLocation.getCity() + "");
        if (aMapLocation.getCity().contains("[")) {
            putString(LOCATION_CITY, "");
        }
        putString(LOCATION_PROVINCE, aMapLocation.getProvince() + "");
        putString(LOCATION_STREET, aMapLocation.getStreet() + "");
        putString(LOCATION_COUNTRY, aMapLocation.getCountry() + "");
    }

    /**
     * 存储高德围栏地址
     */
    public void setFenceSite(String province, String city, String area, String code, String fenceId) {
        Lg.i(TAG, "---设置围栏信息===" + province + city + area + code);
        putString(SpHelper.FENCE_PROVINCE, province);
        putString(SpHelper.FENCE_CITY, city);
        putString(SpHelper.FENCE_AREA, area);
        putString(SpHelper.FENCE_CODE, code);
        putString(SpHelper.FENCE_ID, fenceId);
    }

    /**
     * 获取定位地址详细信息
     * 这儿的code码优先选择用户选择的数据--》 再选择圈内地址-->  在选择定位地址
     */
    public EmergencyLocation getLocation() {
        String lat = getString(LOCATION_LAT);
        String lng = getString(LOCATION_LNG);
        String address = getString(LOCATION_ADDRESS);
        String street = getString(LOCATION_STREET);

        String localCode = getString(LOCATION_AREA_CODE);
        String localCity = getString(LOCATION_CITY);
        String localArea = getString(LOCATION_AREA);
        String localProvince = getString(LOCATION_PROVINCE);

        String SerProvince = getString(SpHelper.AMAPLOCATION_PROVINCE);
        String SerCity = getString(SpHelper.AMAPLOCATION_CITY);
        String SerArea = getString(SpHelper.AMAPLOCATION_AREA);
        String SerCode = getString(SpHelper.AMAPLOCATION_INFO_AREA);

        String fenceProvince = getString(SpHelper.FENCE_PROVINCE);
        String fenceCity = getString(SpHelper.FENCE_CITY);
        String fenceArea = getString(SpHelper.FENCE_AREA);
        String fenceCode = getString(SpHelper.FENCE_CODE);
        Lg.i(TAG, "---getLocation=SerProvince==" + SerProvince);
        Lg.i(TAG, "---getLocation=fenceProvince==" + fenceProvince);
        Lg.i(TAG, "---getLocation=localProvince==" + localProvince);
        EmergencyLocation location = new EmergencyLocation(lat, lng, address);
        location.setStreet(street);
        if (!SerProvince.isEmpty()) {
            Lg.i(TAG, "---getLocation=SerProvince==!SerProvince.isEmpty()");
            location.setProvince(SerProvince);
            location.setCity(SerCity);
            location.setArea(SerArea);
            location.setAreacode(SerCode);
        } else if (!fenceProvince.isEmpty()) {
            Lg.i(TAG, "---getLocation=SerProvince==!fenceProvince.isEmpty()");
            location.setProvince(fenceProvince);
            location.setCity(fenceCity);
            location.setArea(fenceArea);
            location.setAreacode(fenceCode);
        } else {
            Lg.i(TAG, "---getLocation=SerProvince==else");
            location.setProvince(localProvince);
            location.setCity(localCity);
            location.setArea(localArea);
            location.setAreacode(localCode);
        }
        return location;
    }

    /**
     * 获取定位地址详细信息
     * 这儿的code码优先选择圈内地址-->  在选择定位地址
     */
    public EmergencyLocation getFenceLocation() {
        String lat = getString(LOCATION_LAT);
        String lng = getString(LOCATION_LNG);
        String address = getString(LOCATION_ADDRESS);
        String fenceProvince = getString(SpHelper.FENCE_PROVINCE);
        String fenceCity = getString(SpHelper.FENCE_CITY);
        String fenceArea = getString(SpHelper.FENCE_AREA);
        String fenceCode = getString(SpHelper.FENCE_CODE);

        String localCode = getString(LOCATION_AREA_CODE);
        String localCity = getString(LOCATION_CITY);
        String localArea = getString(LOCATION_AREA);
        String localProvince = getString(LOCATION_PROVINCE);

        EmergencyLocation location = new EmergencyLocation(lat, lng, address);
        if (!fenceProvince.isEmpty()) {
            location.setProvince(fenceProvince);
            location.setCity(fenceCity);
            location.setArea(fenceArea);
            location.setAreacode(fenceCode);
        } else {
            location.setProvince(localProvince);
            location.setCity(localCity);
            location.setArea(localArea);
            location.setAreacode(localCode);
        }
        return location;
    }

    /**
     * 获取定位地址详细信息
     * 这儿的code码选择定位地址
     */
    public EmergencyLocation getLocalLocation() {
        String lat = getString(LOCATION_LAT);
        String lng = getString(LOCATION_LNG);
        String address = getString(LOCATION_ADDRESS);
        String street = getString(LOCATION_STREET);
        String localCode = getString(LOCATION_AREA_CODE);
        String localCity = getString(LOCATION_CITY);
        String localArea = getString(LOCATION_AREA);
        String localProvince = getString(LOCATION_PROVINCE);
        EmergencyLocation lccation = new EmergencyLocation(lat, lng, address, localArea, localCode, localCity, localProvince);
        lccation.setStreet(street);
        return lccation;
    }

    public boolean setSysUserName(String sysUser) {
        return putString(SYS_USER_NAME, sysUser);
    }

    public String getSysUserName() {
        return getString(SYS_USER_NAME);
    }

    /**
     * 获取用户选择的地址
     */
    public String[] getAllSite() {
        String provider = getString(SpHelper.AMAPLOCATION_PROVINCE);
        String city = getString(SpHelper.AMAPLOCATION_CITY);
        String area = getString(SpHelper.AMAPLOCATION_AREA);
        String code = getString(SpHelper.AMAPLOCATION_INFO_AREA);
        String[] site = new String[]{provider, city, area, code};
        return site;
    }

    public boolean setIsVerify(int isVerify) {
        return putInt(IS_VERIFY, isVerify);
    }

    public boolean setName(String name) {
        return putString(NAME, name);
    }

    public int getIsVerify() {
        return getInt(IS_VERIFY);
    }

    public String getUserId() {
        return getString(USER_ID);
    }

    public String getUserName() {
        return getString(USER_NAME);
    }

    public String getName() {
        return getString(NAME);
    }

    public String getPhone() {
        return getString(PHONE);
    }

    public String getBirth() {
        return getString(BIRTH);
    }

    public long getLastVersionCheckTime() {
        return getLong(LAST_VERSION_CHECK_TIME);
    }

    public void setLastVersionCheckTime(long time) {
        putLong(LAST_VERSION_CHECK_TIME, time);
    }

    public boolean setShareCommonArray(String shareArray) {
        return putString(SHARE_COMMON_ARRAY, shareArray);
    }

    public String getShareCommonArray() {
        return getString(SHARE_COMMON_ARRAY);
    }

    public boolean addTopicId(String topicId) {
        Set<String> stringSet = new HashSet<>();
        if (getTopicIdSet() != null) {
            stringSet.addAll(getTopicIdSet());
        }
        stringSet.add(topicId);
        return putSet(TOPIC_ID_SET, stringSet);
    }

    public Set<String> getTopicIdSet() {
        return getSet(TOPIC_ID_SET);
    }

    public boolean saveTopicIdSet(Set<String> topicIdSet) {
        return putSet(TOPIC_ID_SET, topicIdSet);
    }

    public boolean clearTopicIdSet() {
        Set<String> tempSet = new HashSet<>();
        return saveTopicIdSet(tempSet);
    }


    public boolean addRedPoint(String friendId) {
        Set<String> redMap = new HashSet<>();
        if (getRedMap() != null) {
            redMap.addAll(getRedMap());
        }
        redMap.add(friendId);
        return putSet(MSG_MAP_NONE, redMap);
    }

    public synchronized boolean deleteRedPoint(String friend) {
        Set<String> reds = getRedMap();
        Iterator<String> iterator = reds.iterator();
        while (iterator.hasNext()){
            if (iterator.next().equals(friend)){
                iterator.remove();
            }
        }
        return putSet(MSG_MAP_NONE, reds);
    }


    public Set<String> getRedMap() {
        return getSet(MSG_MAP_NONE);
    }

    private String getSerProvince() {
        return getString(AMAPLOCATION_PROVINCE);
    }

    private String getSerCity() {
        return getString(AMAPLOCATION_CITY);
    }

    private String getSerArea() {
        return getString(AMAPLOCATION_AREA);
    }


    public int getPatchVersion() {
        return getInt(PATCH_VERSION);
    }

    public void setPatchVersion(int patchVersion) {
        putInt(PATCH_VERSION, patchVersion);
    }

    public int getAppVersion() {
        return getInt(APP_VERSION);
    }

    public void setAppVersion(int appVersion) {
        putInt(APP_VERSION, appVersion);
    }


    public int getWorkingMode() {
        int mode = getInt(WORKING_MODE);
        if (mode < 0) {
            mode = 0;
        }
        return mode;
    }

    public boolean setWorkingMode(int mode) {
        return putInt(WORKING_MODE, mode);
    }

    public boolean putNewNotifyIdSet(String notifyId) {
        Set<String> notifyIdSet = getSet(NEW_NOTIFICATION_ID);
        notifyIdSet.add(notifyId);
        return putSet(NEW_NOTIFICATION_ID, notifyIdSet);
    }

    public Set<String> getNewNotifyIdSet() {
        return getSet(NEW_NOTIFICATION_ID);
    }

    public String getNickName() {
        return getString(NICK_NAME);
    }

    public void setNickName(String nickName) {
        putString(NICK_NAME, nickName);
    }

    public String getUnoionId() {
        return getString(UNOION_ID);
    }
    public void setUnoionId(String nickName) {
        putString(UNOION_ID, nickName);
    }

    public String getWxLoginState() {
        return getString(WX_LOGIN_STATE);
    }
    public void setWxLoginState(String wxLoginState) {
        putString(WX_LOGIN_STATE, wxLoginState);
    }

    public void setHubCurrentHost(String hubCurrentHost){
        putString(HUB_CURRENT_HOST, hubCurrentHost);
    }

    public String getHubCurrentHost(){
        return getString(HUB_CURRENT_HOST);
    }

    public void setHubBackupHost(String hubBackupHost){
        putString(HUB_BACKUP_HOST, hubBackupHost);
    }

    public String getHubBackupHost(){
        return getString(HUB_BACKUP_HOST);
    }

    public String getFacePhoto(){
        return getString(FACE_PHOTO);
    }

    public String getSecret(){
        return getString(SECRET);
    }

    public boolean setScannerToken(String token){
        return putString(SCANNER_TOKEN, token);
    }

    public String getScannerToken(){
        return getString(SCANNER_TOKEN);
    }


    public boolean myInfoHasUpdate(){
        return putInt(MY_INFO_HAS_UPDATE, 1);
    }

    public boolean checkMyInfoUpdateStatus(){
        if (getInt(MY_INFO_HAS_UPDATE) > 0){
            putInt(MY_INFO_HAS_UPDATE, 0);
            return true;
        }else {
            return false;
        }
    }

    public boolean isFirst(){
        boolean isFirst = !getBoolean(APP_IS_USED);
        if (isFirst){
            putBoolean(APP_IS_USED, true);
        }
        return isFirst;
    }

    public boolean setLastAlarmFinishTime(long time){
        Lg.i(TAG, "---setLastAlarmFinishTime===" + time);
        return putLong(LAST_ALARM_FINISH_TIME, time);
    }

    public long getLastAlarmFinishTime(){
        return getLong(LAST_ALARM_FINISH_TIME);
    }

    public void setSosCode(Boolean hasSOS) {
        String areaCode = SpHelper.getInstance().getLocation().getAreacode();
        Set<String> sosSet = getSet(SOS_CODE);
        Iterator<String> iterator = sosSet.iterator();
        while (iterator.hasNext()){
            if (iterator.next().contains(areaCode)){
                iterator.remove();
            }
        }
        sosSet.add(areaCode + "-" + hasSOS);
        putSet(SOS_CODE, sosSet);
    }

    public boolean hasSos(){
        Set<String> sosSet = getSet(SOS_CODE);
        Iterator<String> iterator = sosSet.iterator();
        while (iterator.hasNext()){
            String sosCode = iterator.next();
            if (sosCode.contains(SpHelper.getInstance().getLocation().getAreacode())){
                return Boolean.parseBoolean(sosCode.split("-")[1]);
            }
        }

        return false;
    }
}
